package com.yhj.wchat.netty;


import com.yhj.wchat.entity.po.UserInfo;
import com.yhj.wchat.mapper.UserInfoMapper;
import com.yhj.wchat.message.MessageHandler;
import com.yhj.wchat.redis.RedisComponent;
import com.yhj.wchat.utils.ChannelContextUtils;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@ChannelHandler.Sharable
@Slf4j
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    // 与 WsAuthHandler 中同名的 Key（名字一致即可）
    private static final AttributeKey<String> USER_ID = AttributeKey.valueOf("USER_ID");

    @Resource
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisComponent redisComponent;
    @Resource
    private MessageHandler messageHandler;
    @Resource
    private ChannelContextUtils channelContextUtils;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 鉴权发生在 WsAuthHandler 里，这里可能还拿不到 userId
        String userId = ctx.channel().attr(USER_ID).get();
       // log.info("有新的连接加入.........{}", userId);
        // 登录时间已在 WsAuthHandler 里更新，这里不再重复更新
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        String userId = ctx.channel().attr(USER_ID).get();
        log.info("有连接断开{}.........",userId);
        channelContextUtils.closeContext(userId);
        UserInfo userInfo = new UserInfo();
        userInfo.setLastOffTime(System.currentTimeMillis());
        userInfoMapper.updateByUserId(userInfo,userId);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        log.info("收到消息:{}",text);
        if("ping".equals(text)){
            return;
        }
    }
}
